/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.emergency.command.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.emergency.command.entity.ErAccidentEntity;
import com.hopes.bizz.emergency.command.entity.ErAssessDetailEntity;
import com.hopes.bizz.emergency.command.entity.ErDocumentationRecordEntity;
import com.hopes.bizz.emergency.command.mapper.ErAccidentMapper;
import com.hopes.bizz.emergency.command.mapper.ErAssessDetailMapper;
import com.hopes.bizz.emergency.command.mapper.ErDocumentationRecordMapper;
import com.hopes.bizz.emergency.command.service.ErAccidentService;
import com.hopes.bizz.emergency.command.vo.ErEmergencyHandleWordVO;
import com.hopes.bizz.emergency.common.constant.PlanDicConstant;
import com.hopes.bizz.emergency.resources.mapper.ErTeamMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应急事故
 *
 * @author cx
 * @date 2024-01-19 13:18:22
 */
@Service
@RequiredArgsConstructor
public class ErAccidentServiceImpl extends ServiceImpl<ErAccidentMapper, ErAccidentEntity> implements ErAccidentService {

    private final ErDocumentationRecordMapper erDocumentationRecordMapper;
    private final ErAssessDetailMapper erAssessDetailMapper;

    @Override
    public void exportWord(Long accidentId, HttpServletResponse response)  {
        // 获取数据
        ErAccidentEntity erAccidentEntity = this.getById(accidentId);
        ErEmergencyHandleWordVO tableInfo = new ErEmergencyHandleWordVO();
        BeanUtil.copyProperties(erAccidentEntity,tableInfo);
        LambdaQueryWrapper<ErDocumentationRecordEntity> documentationWrapper = Wrappers.<ErDocumentationRecordEntity>lambdaQuery().eq(ErDocumentationRecordEntity::getAccidentId, accidentId);
        ErDocumentationRecordEntity documentationRecordEntity = erDocumentationRecordMapper.selectOne(documentationWrapper);
        LambdaQueryWrapper<ErAssessDetailEntity> assessWrapper = Wrappers.<ErAssessDetailEntity>lambdaQuery().eq(ErAssessDetailEntity::getAccidentId, accidentId);
        List<ErAssessDetailEntity> erAssessDetailList = erAssessDetailMapper.selectList(assessWrapper);
        List<ErAssessDetailEntity> eventAssessList = erAssessDetailList.stream()
                .filter(entity -> entity.getAssessType().equals(PlanDicConstant.ASSESS_TYPE_EVENT))
                .collect(Collectors.toList());
        List<ErAssessDetailEntity> abilityAssessList = erAssessDetailList.stream()
                .filter(entity -> entity.getAssessType().equals(PlanDicConstant.ASSESS_TYPE_ABILITY))
                .collect(Collectors.toList());
        List<ErAssessDetailEntity> comprehensiveAssessList = erAssessDetailList.stream()
                .filter(entity -> entity.getAssessType().equals(PlanDicConstant.ASSESS_TYPE_COMPREHENSIVE))
                .collect(Collectors.toList());

        // 构建为word导出的数据
        ErEmergencyHandleWordVO.ErEmergencyHandleWordVOBuilder builder = ErEmergencyHandleWordVO.builder();
        ErEmergencyHandleWordVO wordVo = builder.orgIdStr(tableInfo.getOrgIdStr())
                .companyAddress(tableInfo.getCompanyAddress())
                .accidentName(tableInfo.getAccidentName())
                .accidentTypeDic(tableInfo.getAccidentTypeStr())
                .accidentOccurrenceTime(tableInfo.getAccidentOccurrenceTime())
                .accidentConfirmTime(tableInfo.getAccidentConfirmTime())
                .alarmPeople(tableInfo.getAlarmPeople())
                .alarmTime(tableInfo.getAlarmTime())
                .alarmPeoplePhone(tableInfo.getAlarmPeoplePhone())
                .accidentOrigin(tableInfo.getAccidentOrigin())
                .rescueStartTime(tableInfo.getRescueStartTime())
                .directLoss(tableInfo.getDirectLoss())
                .minorWoundNum(tableInfo.getMinorWoundNum())
                .severeWoundNum(tableInfo.getSevereWoundNum())
                .treppedNum(tableInfo.getTreppedNum())
                .missingNum(tableInfo.getMissingNum())
                .dieNum(tableInfo.getDieNum())
                .receiveAlarmPeople(tableInfo.getReceiveAlarmPeople())
                .accidentDesc(tableInfo.getAccidentDesc())
                .accidentHandleOpinion(tableInfo.getAccidentHandleOpinion())
                .isStartPlan(tableInfo.getIsStartPlanStr())
                .planIdDic(tableInfo.getPlanIdStr())
                .planAccidentType(tableInfo.getPlanAccidentType())
                .accidentLevel(tableInfo.getAccidentLevel())
                .responseLevel(tableInfo.getResponseLevel())
                .evacuationRadius(tableInfo.getEvacuationRadius())
                .startPeople(tableInfo.getStartPeople())
                .startTime(tableInfo.getStartTime())
                .progressDesc(tableInfo.getProgressDesc())
                .startProcessDesc(tableInfo.getStartProcessDesc())
                .commander(documentationRecordEntity.getCommander())
                .closeTime(documentationRecordEntity.getCloseTime())
                .closeDesc(documentationRecordEntity.getCloseDesc())
                .eventAssess(eventAssessList)
                .abilityAssess(abilityAssessList)
                .comprehensiveAssess(comprehensiveAssessList)
                .build();
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", wordVo);
        ClassPathResource resource = new ClassPathResource("file/应急处置报告模板.docx");
        response.setContentType("application/octet-stream; charset=UTF-8");
        LoopRowTableRenderPolicy rowPolicy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("data.eventAssess", rowPolicy)
                .bind("data.abilityAssess", rowPolicy)
                .bind("data.comprehensiveAssess", rowPolicy)
                .useSpringEL()
                .build();

        try {
            XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream(), config).render(map);
            template.writeAndClose(response.getOutputStream());
        } catch (IOException e) {
            log.error("动土安全作业票导出word失败",e);
        }

    }
}